package com.zzh.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.hammera.common.baseUI.BaseView


/**
 * Created by din on 2018/8/7.
 * <p>
 * Email: godcok@163.com
 *
 */
abstract class BaseFragment : Fragment(), BaseView {
    protected var rootView: View? = null


    /**
     * Fragment的View加载完毕的标记
     */
    protected var isViewInitiated: Boolean = false
    /**
     * Fragment对用户可见的标记
     */
    protected var isVisibleToUser: Boolean = false
    /**
     * 是否懒加载
     */
    protected var isDataInitiated: Boolean = false

    /**
     * 是否加载过View
     */
    protected var isInitView: Boolean = false

    /**
     * 获取UI XML
     */
    abstract fun getLayoutUI(): Int


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (rootView == null)
            rootView = inflater.inflate(getLayoutUI(), container, false)
        if (arguments != null) {
            initParams()
        }
        return rootView
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        isViewInitiated = true
        performShowFragment()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (!isInitView) {
            initView()
            isInitView = true

        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        this.isVisibleToUser = isVisibleToUser
        performShowFragment()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
    }

    /**
     * 准备数据
     */
    abstract fun prepareData()

    fun performHideFragment() {

    }

    var mIsShown = false
    fun performShowFragment() {
        if (getUserVisibleHint() && isViewInitiated && !isDataInitiated) {
            onFragmentShow()
            isDataInitiated = true;
        }

    }

    fun onFragmentShow() {
        prepareData()
    }


    fun onFragmentHidden() {
        mIsShown = false
    }

    open fun initParams() {

    }

    abstract fun initView()

    fun <T : View> findViewById(id: Int): T? {
        return (rootView?.findViewById(id) as T?)
    }
}